package com.china08.yxyapi.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aspose.words.net.System.Data.DataColumnCollection;
import com.aspose.words.net.System.Data.DataRow;
import com.aspose.words.net.System.Data.DataTable;
import com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper.ZujuanPaperGenerateController.DownLoadQuesModel;

/**
 * 生成试卷的实体类
 */
// @Component
public class DownWordPaper {

    private static final Logger LOGGER = LoggerFactory.getLogger(DownWordPaper.class);
    // 下载试卷的存储目录
    // @Value("${zujuan.storage.upload.paper}")
    private String downloadDir;

    // private String downloadDir = "/mnt/gfs/paper/upload";

    public String getDownloadDir() {
        return downloadDir;
    }

    public void setDownloadDir(String downloadDir) {
        this.downloadDir = downloadDir;
    }

    // 试卷名称
    private String paperName;

    // 试卷类型
    private String paperType;

    // 试卷的尺寸
    private String paperSize;

    // 主标题
    private String mainTitle;

    // 副标题
    private String subTitle;

    // 试卷信息栏
    private String paperInfo;

    // 考生输入栏
    private String studentInfo;

    // 注意事项
    private String attentionInfo;

    // 第一卷说明
    private String InstructionFirst;

    // 第二卷说明
    private String InstructionTwo;

    // 第一大题注释
    private String NotesFirst;

    // 第二大题注释
    private String NotesTwo;

    // 第三大题注释
    private String NotesThree;

    // 第四大题注释
    private String NotesFour;

    // 基本设置
    private List<String> basicSettingList;

    // 生成试卷的工具类
    private WordUtil wordUtil;

    // 单选
    private List<DownLoadQuesModel> danxuan;

    // 多选
    private List<DownLoadQuesModel> duoxuan;

    // 填空
    private List<DownLoadQuesModel> tiankong;

    // 解答
    private List<DownLoadQuesModel> jieda;

    public List<DownLoadQuesModel> getDanxuan() {
        return danxuan;
    }

    public void setDanxuan(List<DownLoadQuesModel> danxuan) {
        this.danxuan = danxuan;
    }

    public List<DownLoadQuesModel> getDuoxuan() {
        return duoxuan;
    }

    public void setDuoxuan(List<DownLoadQuesModel> duoxuan) {
        this.duoxuan = duoxuan;
    }

    public List<DownLoadQuesModel> getTiankong() {
        return tiankong;
    }

    public void setTiankong(List<DownLoadQuesModel> tiankong) {
        this.tiankong = tiankong;
    }

    public List<DownLoadQuesModel> getJieda() {
        return jieda;
    }

    public void setJieda(List<DownLoadQuesModel> jieda) {
        this.jieda = jieda;
    }

    public String getPaperName() {
        return paperName;
    }

    public void setPaperName(String paperName) {
        this.paperName = paperName;
    }

    public String getPaperType() {
        return paperType;
    }

    public void setPaperType(String paperType) {
        this.paperType = paperType;
    }

    public String getPaperSize() {
        return paperSize;
    }

    public void setPaperSize(String paperSize) {
        this.paperSize = paperSize;
    }

    public String getMainTitle() {
        return mainTitle;
    }

    public void setMainTitle(String mainTitle) {
        this.mainTitle = mainTitle;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

    public String getPaperInfo() {
        return paperInfo;
    }

    public void setPaperInfo(String paperInfo) {
        this.paperInfo = paperInfo;
    }

    public String getStudentInfo() {
        return studentInfo;
    }

    public void setStudentInfo(String studentInfo) {
        this.studentInfo = studentInfo;
    }

    public String getAttentionInfo() {
        return attentionInfo;
    }

    public void setAttentionInfo(String attentionInfo) {
        this.attentionInfo = attentionInfo;
    }

    public String getInstructionFirst() {
        return InstructionFirst;
    }

    public void setInstructionFirst(String instructionFirst) {
        InstructionFirst = instructionFirst;
    }

    public String getInstructionTwo() {
        return InstructionTwo;
    }

    public void setInstructionTwo(String instructionTwo) {
        InstructionTwo = instructionTwo;
    }

    public String getNotesFirst() {
        return NotesFirst;
    }

    public void setNotesFirst(String notesFirst) {
        NotesFirst = notesFirst;
    }

    public String getNotesTwo() {
        return NotesTwo;
    }

    public void setNotesTwo(String notesTwo) {
        NotesTwo = notesTwo;
    }

    public String getNotesThree() {
        return NotesThree;
    }

    public void setNotesThree(String notesThree) {
        NotesThree = notesThree;
    }

    public String getNotesFour() {
        return NotesFour;
    }

    public void setNotesFour(String notesFour) {
        NotesFour = notesFour;
    }

    public List<String> getBasicSettingList() {
        return basicSettingList;
    }

    public void setBasicSettingList(List<String> basicSettingList) {
        this.basicSettingList = basicSettingList;
    }

    // 生成一个模板
    public void GeneratePaper(String docversion) throws Exception {
        try {
            LOGGER.info("=====================================开始生成word：");
            // 下载文件夹 年月日
            String path = getPath();
            String savePath = getDownloadDir() + path;
            File file = new File(savePath);
            FileUtils.forceMkdir(file);

            LOGGER.info("======================================创建目录成功：" + savePath);
            // if (!file.exists()) {
            // file.mkdirs();
            // }
            String realpath = savePath + File.separator + getPaperName();

            wordUtil = new WordUtil();
            wordUtil.Docversion = docversion.equals("doc") ? 2003 : 2007;
            LOGGER.info("======================================生成文件路径为：" + realpath);
            wordUtil.Open(getDownloadDir());
            wordUtil.ClearBookMark();
            WritePaperHead();
            WritePaperBody();
            wordUtil.SaveAs(realpath);
        } catch (Exception e) {
            LOGGER.error("=====================================生成word失败：" + e);
            throw new Exception("=====================================生成word失败");
        }
    }

    // 试卷卷头
    public void WritePaperHead() throws Exception {
        wordUtil.setPaperSize(paperSize);
        wordUtil.Builder();
        wordUtil.SetHeade("装订线2", "装订线");
        // 主标题
        if (basicSettingList.contains("4")) {
            wordUtil.InsertText("绝密★启用前", 14, true, "left");
        }
        // 主标题
        if (basicSettingList.contains("1")) {
            wordUtil.InsertText(this.mainTitle, 15, true, "center");
        }
        // 副标题
        if (basicSettingList.contains("2")) {
            wordUtil.InsertText(this.subTitle, 12, false, "center");
        }
        // 试卷信息栏
        if (basicSettingList.contains("5")) {
            wordUtil.InsertText(this.paperInfo, 12, false, "center");
        }
        // 考生输入栏
        if (basicSettingList.contains("6")) {
            wordUtil.InsertText(this.studentInfo, 12, false, "center");
        }
        // wordUtil.InsertLineBreak();
        // 誉分栏
        if (basicSettingList.contains("7")) {
            wordUtil.InsertTable(getScoreTable(), true);
        }
        // 注意事项
        if (basicSettingList.contains("8")) {
            wordUtil.InsertText("注意事项：", 12, false, "left");
            this.attentionInfo = this.attentionInfo.replace("</br>", "\n");
            wordUtil.InsertText(this.attentionInfo, 12, false, "left");
        }
    }

    // 绘制誉分栏表格
    private DataTable getScoreTable() {
        DataTable dt = new DataTable("score");
        DataColumnCollection columns = dt.getColumns();
        columns.add("1");
        columns.add("2");
        columns.add("3");
        columns.add("4");
        columns.add("5");
        columns.add("6");
        DataRow newRow1 = dt.newRow();
        newRow1.set(0, "题号");
        newRow1.set(1, "一");
        newRow1.set(2, "二");
        newRow1.set(3, "三");
        newRow1.set(4, "四");
        newRow1.set(5, "总分");
        dt.getRows().add(newRow1);

        DataRow newRow2 = dt.newRow();
        newRow2.set(0, "得分");
        newRow2.set(1, "");
        newRow2.set(2, "");
        newRow2.set(3, "");
        newRow2.set(4, "");
        newRow2.set(5, "");
        dt.getRows().add(newRow2);
        return dt;
    }

    // 试卷主体
    public void WritePaperBody() throws Exception {
        // 写入1卷的卷头
        wordUtil.InsertText("第I卷（选择题）", 12, true, "center");
        if (basicSettingList.contains("9")) {
            wordUtil.InsertText(this.InstructionFirst, 12, false, "left");
        }

        // 单选
        if (CollectionUtils.isNotEmpty(danxuan)) {
            String quesTypeName = "一、单选题";
            if (basicSettingList.contains("10")) {
                quesTypeName = quesTypeName + this.NotesFirst;
            }
            // 大题评分区
            if (basicSettingList.contains("11")) {
                wordUtil.InsertScoreTable(true, true, quesTypeName);
            }
            wordUtil.InsertLineBreak();
            for (DownLoadQuesModel ques : danxuan) {
                wordUtil.InsertHtml(convertQues2Html(ques), 12, false, "left");
                wordUtil.InsertLineBreak();
                if (this.paperType.equals("teacher")) {
                    wordUtil.InsertHtml(convertAnswer2Html(ques), 9, false, "left");
                }
                wordUtil.InsertLineBreak();
            }
        }

        // 多选
        if (CollectionUtils.isNotEmpty(duoxuan)) {
            String quesTypeName = "二、多选题";
            if (basicSettingList.contains("10")) {
                quesTypeName = quesTypeName + this.NotesTwo;
            }
            // 大题评分区
            if (basicSettingList.contains("11")) {
                wordUtil.InsertScoreTable(true, true, quesTypeName);
            }
            wordUtil.InsertLineBreak();
            for (DownLoadQuesModel ques : duoxuan) {
                wordUtil.InsertHtml(convertQues2Html(ques), 12, false, "left");
                wordUtil.InsertLineBreak();
                if (this.paperType.equals("teacher")) {
                    wordUtil.InsertHtml(convertAnswer2Html(ques), 9, false, "left");
                }
                wordUtil.InsertLineBreak();
            }
        }

        // 写入2卷的卷头
        wordUtil.InsertText("第II卷（非选择题）", 12, true, "center");
        if (basicSettingList.contains("9")) {
            wordUtil.InsertText(this.InstructionTwo, 12, false, "left");
        }

        // 填空
        if (CollectionUtils.isNotEmpty(tiankong)) {
            String quesTypeName = "三、填空题";
            if (basicSettingList.contains("10")) {
                quesTypeName = quesTypeName + this.NotesThree;
            }
            // 大题评分区
            if (basicSettingList.contains("11")) {
                wordUtil.InsertScoreTable(true, true, quesTypeName);
            }
            wordUtil.InsertLineBreak();
            for (DownLoadQuesModel ques : tiankong) {
                wordUtil.InsertHtml(convertQues2Html(ques), 12, false, "left");
                wordUtil.InsertLineBreak();
                if (this.paperType.equals("teacher")) {
                    wordUtil.InsertHtml(convertAnswer2Html(ques), 9, false, "left");
                }
                wordUtil.InsertLineBreak();
            }
        }

        // 解答
        if (CollectionUtils.isNotEmpty(jieda)) {
            String quesTypeName = "四、解答题";
            if (basicSettingList.contains("10")) {
                quesTypeName = quesTypeName + this.NotesFour;
            }
            // 大题评分区
            if (basicSettingList.contains("11")) {
                wordUtil.InsertScoreTable(true, true, quesTypeName);
            }
            wordUtil.InsertLineBreak();
            for (DownLoadQuesModel ques : jieda) {
                wordUtil.InsertHtml(convertQues2Html(ques), 12, false, "left");
                wordUtil.InsertLineBreak();
                if (this.paperType.equals("teacher")) {
                    wordUtil.InsertHtml(convertAnswer2Html(ques), 9, false, "left");
                }
                wordUtil.InsertLineBreak();
            }
        }

        // 答案在卷尾
        List<DownLoadQuesModel> allQues = new ArrayList<DownLoadQuesModel>();
        allQues.addAll(danxuan);
        allQues.addAll(duoxuan);
        allQues.addAll(tiankong);
        allQues.addAll(jieda);
        if (this.paperType.equals("normal")) {
            wordUtil.InsertText("试卷答案", 18, true, "center");
            for (DownLoadQuesModel ques : allQues) {
                wordUtil.InsertHtml(convertAnswer2Html(ques), 12, false, "left");
                wordUtil.InsertLineBreak();
            }
        }

    }

    /**
     * 把答案内容转成html
     */
    private String convertAnswer2Html(DownLoadQuesModel ques) {
        // String cssstyle = "<link rel='stylesheet'
        // href='D:/temp/paper/questionglobal.css' type='text/css'/>" + "";
        String cssstyle = "";
        String answerPrefix = "<div class='answer-single' style='font-family:宋体;font-size:16px'>";
        String answerSuffix = "</div>";
        String answerhtml = answerPrefix + ques.analysis + answerSuffix;
        return cssstyle + answerhtml;
    }

    /**
     * 把试题内容转成html
     */
    private String convertQues2Html(DownLoadQuesModel ques) {
        // String cssstyle = "<link rel='stylesheet'
        // href='D:/temp/paper/questionglobal.css' type='text/css'/>" + "";
        String cssstyle = "";
        String quesPrefix = "<div class='ques-bo'  style='font-family:宋体;font-size:16px'>";
        String quesSuffix = "</div>";
        String html = quesPrefix + ques.quesBody + quesSuffix;
        return cssstyle + html;
    }

    /**
     * 年+月+日 路径
     * 
     * @return
     */
    private String getPath() {
        StringBuffer path = new StringBuffer("/");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Date date = c.getTime();
        String pathDate = sdf.format(date);
        String year = pathDate.toString().substring(0, 4);
        path.append(year + "/");
        String mouth = pathDate.toString().substring(5, 7);
        path.append(mouth + "/");
        String day = pathDate.toString().substring(8, 10);
        path.append(day);
        String pathString = path.toString();
        return pathString;
    }
}
